//
//  SPBluetoothManager.m
//  Spinning
//
//  Created by Neil on 2018/1/25.
//  Copyright © 2018年 com. All rights reserved.
//

#import "SPBluetoothManager.h"
#import <CommonCrypto/CommonCryptor.h>

#define BLE_SEND_MAX_LEN 20
#define keyStr @"11223344552018051111176677889901"


@interface SPBluetoothManager ()

@property (nonatomic, strong) BabyBluetooth *bluetoothManager;

@property (nonatomic, strong) NSMutableArray *characteristicArray;


@property (nonatomic, strong) CBCharacteristic *characteristicWrite;
@property (nonatomic, strong) CBCharacteristic *characteristicNotify;



@end

@implementation SPBluetoothManager {

    
}

#pragma mark - setter and getter
- (BabyBluetooth *)bluetoothManager {
    if (!_bluetoothManager) {
        _bluetoothManager = [BabyBluetooth shareBabyBluetooth];
    }
    return _bluetoothManager;
}


// 身份验证
- (NSMutableString *)dataMStr {
    if (!_dataMStr) {
        _dataMStr = [NSMutableString string];
    }
    return _dataMStr;
}

// 充值
- (NSMutableString *)dataMStrRecharge {
    if (!_dataMStrRecharge) {
        _dataMStrRecharge = [NSMutableString string];
    }
    return _dataMStrRecharge;
}


+ (instancetype)shareManager {
    static SPBluetoothManager *manager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[SPBluetoothManager alloc] init];
    });
    return manager;
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        

        [self bluetoothDelegate];
        
        // 日志测试
        self.mStr = [NSMutableString string];


    }
    return self;
}




#pragma mark - 蓝牙连接方法

//- (void)startConnect {
//    self.bluetoothManager.scanForPeripherals().connectToPeripherals().discoverServices().discoverCharacteristics().begin();
//}

- (void)startScan {
    self.bluetoothManager.scanForPeripherals().begin(); 
}

- (void)disconnect {
    
    [self.bluetoothManager cancelAllPeripheralsConnection];

}

- (void)connectToPeripheral:(CBPeripheral *)peripheral {
//    [self disconnect];
    self.bluetoothManager.having(peripheral).then.connectToPeripherals().discoverServices().discoverCharacteristics().begin();
    [self.bluetoothManager cancelScan];
}


#pragma mark - bluetooth settings
- (void)bluetoothDelegate { 
    
    GET_WEAKSELF;
    __strong typeof(self) strongSelf = weakSelf;

    [self.bluetoothManager setBlockOnCentralManagerDidUpdateState:^(CBCentralManager *central) {
        weakSelf.bluetoothOpen = central.state == CBCentralManagerStatePoweredOn;
        if ([weakSelf.delegate respondsToSelector:@selector(bluetoothStateOpen)]) {
            [weakSelf.delegate bluetoothStateOpen];
        }
    }];
    
    
    [self.bluetoothManager setFilterOnDiscoverPeripherals:^BOOL(NSString *peripheralName, NSDictionary *advertisementData, NSNumber *RSSI) {
        

        NSLog(@"peripheralName%@",peripheralName);
        BOOL isSpinning = NO;
        
        if (self.deviceType1 == 0) {
            isSpinning = [peripheralName hasPrefix:@"HH01"];

        }
        else {
//            isSpinning = [peripheralName hasPrefix:@"HHIC"];

        }
        return isSpinning;

//        return YES;


    }];
    
    [self.bluetoothManager setFilterOnConnectToPeripherals:^BOOL(NSString *peripheralName, NSDictionary *advertisementData, NSNumber *RSSI) {
        

        NSLog(@"peripheralName%@",peripheralName);

        BOOL isSpinning = NO;

        if (self.deviceType1 == 0) {
            isSpinning = [peripheralName hasPrefix:@"HH01"];

        }
        else {
//            isSpinning = [peripheralName hasPrefix:@"HHIC"];

        }
        return isSpinning;
//        return YES;

    }];

    [self.bluetoothManager setBlockOnDiscoverToPeripherals:^(CBCentralManager *central, CBPeripheral *peripheral, NSDictionary *advertisementData, NSNumber *RSSI) {
        NSLog(@"find device ====>>>  name:%@, UUID:%@", peripheral.name, peripheral.identifier);
        if (peripheral.name.length > 0) {
            if ([weakSelf.delegate respondsToSelector:@selector(bluetoothDiscoveredPeripheral:)]) {
                [weakSelf.delegate bluetoothDiscoveredPeripheral:peripheral];
            }
        }
    }];
    
    //  连接到设备
    [self.bluetoothManager setBlockOnConnected:^(CBCentralManager *central, CBPeripheral *peripheral) {
        
        [weakSelf.bluetoothManager cancelScan];
//        strongSelf->_currentDeviceIsQidong = [peripheral.name hasPrefix:@"QiDong"];
        weakSelf.connected = YES;
        weakSelf.fitNowPeripheral = peripheral;

        if ([strongSelf.delegate respondsToSelector:@selector(bluetoothConnected:)]) {
            [strongSelf.delegate bluetoothConnected:peripheral];
        }
        
//        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//
//            [weakSelf verifyDevice];
//
//        });
    }];

    
    //设置发现设备service的Characteristics的委托
    [self.bluetoothManager setBlockOnDiscoverCharacteristics:^(CBPeripheral *peripheral, CBService *service, NSError *error) {
        NSLog(@"===service UUID:%@",service.UUID);
        NSLog(@"****************%@",service.UUID.UUIDString);
        
        
        if ([service.UUID.UUIDString isEqualToString:@"FF12"]) {
            
            for (CBCharacteristic *c in service.characteristics) {
                
                NSLog(@"===Characteristic UUID:%@",c.UUID);

                if ([c.UUID.UUIDString isEqualToString:@"FF01"]) {

                    weakSelf.characteristicWrite = c;
                    [weakSelf verifyDevice];

                }
                
                if ([c.UUID.UUIDString isEqualToString:@"FF02"]) {
                    
                    weakSelf.characteristicNotify = c;
                    __block int i = 0;

                    if (!c.isNotifying) {
                        [weakSelf.bluetoothManager notify:peripheral characteristic:c block:^(CBPeripheral *peripheral, CBCharacteristic *characteristics, NSError *error) {
                            
                            // 读写分开则在这里返回
                            NSLog(@"notify changed value is:%@, characteristic:%@, 序号:%d\n", characteristics.value, characteristics.UUID, i);
                            i++;
                            
                            if (!weakSelf.isRechargeConfirm) {
                                [weakSelf handleValueWithBluetoothData:characteristics.value];

                            }
//                            [weakSelf handleValueWithBluetoothData:characteristics.value];

                            
                        }];
                    }

                }
            }
            

        }
        
     
    }];
    
//    [self bluetoothWriteCallBack];
    
    [self.bluetoothManager setBlockOnDisconnect:^(CBCentralManager *central, CBPeripheral *peripheral, NSError *error) {
        
//        if (weakSelf.characteristicNotify) {
//
//            [weakSelf.bluetoothManager cancelNotify:weakSelf.fitNowPeripheral characteristic:weakSelf.characteristicNotify];
//
//        }
        weakSelf.fitNowPeripheral = nil;
        weakSelf.characteristicWrite = nil;
        weakSelf.characteristicNotify = nil;
        weakSelf.connected = NO;
        if ([strongSelf.delegate respondsToSelector:@selector(bluetoothDisconnected)]) {
            [strongSelf.delegate bluetoothDisconnected];
        }
        NSLog(@"蓝牙断开！");
    }];
    
}



#pragma mark - write value to bluetooth

//  蓝牙返回写数据结果(读写一起才用到)
//- (void)bluetoothWriteCallBack {
//    GET_WEAKSELF;
//    __strong typeof(self) strongSelf = weakSelf;
//
//    [self.bluetoothManager setBlockOnDidWriteValueForCharacteristic:^(CBCharacteristic *characteristic, NSError *error) {
//
//        NSLog(@"DidWrite");
//
//        [weakSelf handleValueWithBluetoothData:characteristic.value];
//
//
//    }];
//}

- (void)handleValueWithBluetoothData:(NSData *)data {
    
    NSLog(@"数据有回。。。。。。。。。。");

    if (self.isRecharge) {
        
        NSString *oringinStr = @"68a210a1e1000000000059684a10cce37672cfc9e23dbc4c8ffa23564707f6c9e8646403a5b89dd7b9206d280c44057db83048825fb14284bba927db5365b44946c7ffcd722ed2c9a3de09f193856de17f64460345a38a397f4eaca65e13c4271d46750415c0e520abc9fb49d016";
        
//        NSString *oringinStr = @"68a201e1a100000000001468519bf3ce5c702e2f11fe66006797ad813eb1e33a5cf9cac86aa555827b152e10641668a210a1e1000000000059684a10cce37672cfc9e23dbc4c8ffa23564707f6c9e8646403a5b89dd7b9206d280c44057db83048825fb14284bba927db5365b44946c7ffcd722ed2c9a3de09f193856de17f64460345a38a397f4eaca64dfe349e2a2b1698445a0abea9b5b552d016";

    

        
        // 充值回的数据处理
        NSString *hexString = [self hexStringWithData:data];
        [self.dataMStrRecharge appendString:hexString];
        NSLog(@"self.dataMStrRecharge:%@,位数：%ld",self.dataMStrRecharge, self.dataMStrRecharge.length);

        
        // 数据接收结束
        if (self.dataMStrRecharge.length == oringinStr.length) {
            
            
            /*
            // 数据域数据
            NSString *str3 = [self.dataMStrRecharge substringWithRange:NSMakeRange(24, self.dataMStrRecharge.length-24-4)];
            NSLog(@"str1:%@",str3);

            NSMutableData *data1 = [self convertHexStrToData:str3];
            
            // 秘钥
            NSMutableData *keyData = [self convertHexStrToData:keyStr];
            
            // 解密
            NSMutableData *data2 = [self AES_NEW_AESDecrypt:data1 password:keyData];
            
            NSString *str4 = [self hexStringWithData:data2];
            NSLog(@"str4:%@",str4);
            
            NSUInteger length = 0;
            
            // 命令类型
            NSString *subStr1 = [str4 substringWithRange:NSMakeRange(0, 2*1)];
            NSLog(@"命令类型:%@",subStr1);
            length = length + subStr1.length;
            
            // 卡区域号
            NSString *subStr2 = [str4 substringWithRange:NSMakeRange(length, 2*3)];
            NSLog(@"卡区域号:%@",subStr2);
            length = length + subStr2.length;
            
            // 卡ID号
            NSString *subStr3 = [str4 substringWithRange:NSMakeRange(length, 2*5)];
            NSLog(@"卡ID号:%@",subStr3);
            length = length + subStr3.length;
            
            // 表具剩余金额
            NSString *subStr4 = [str4 substringWithRange:NSMakeRange(length, 2*4)];
            NSLog(@"表具剩余金额:%@",subStr4);
            length = length + subStr4.length;
            
            // 充值状态
            NSString *subStr5 = [str4 substringWithRange:NSMakeRange(length, 2*1)];
            NSLog(@"充值状态:%@",subStr5);
            length = length + subStr5.length;
            
            // 表内当前充值次数
            NSString *subStr6 = [str4 substringWithRange:NSMakeRange(length, 2*2)];
            NSLog(@"表内当前充值次数:%@",subStr6);
            length = length + subStr6.length;
            
            self.dataMStrRecharge = nil;
            
            // 写卡结果
            [[NSNotificationCenter defaultCenter] postNotificationName:@"kWriteCardNotification" object:subStr5];
             */
            [self rechargeConfirm];
            self.dataMStrRecharge = nil;
        }
    }
    else {

        NSString *oringinStr = @"68a201e1a1488500000000010368ebac4255b76e786598a1bee84ff4b19cc21668a201e1a100000000012168ca228a1e4b843c60b01fae1233daad092535d3330b7b6079a5cc0822253c69bdbcfadd6a386ed28c4b877d6e225fa48c93856de17f64460345a38a397f4eaca681bb2d864b183cfc4708713c09f816ac93856de17f64460345a38a397f4eaca693856de17f64460345a38a397f4eaca63ab4a7dd7c175899d3a210edc417d575f6724231f5ef0bbe25c7de94f2ade0277f26";
        
        // 身份验证回的数据处理
        NSString *hexString = [self hexStringWithData:data];
        [self.dataMStr appendString:hexString];
        NSLog(@"self.dataMStr:%@",self.dataMStr);
        
        // 数据接收结束
        if (self.dataMStr.length == oringinStr.length) {
            
            NSArray *arr = [self.dataMStr componentsSeparatedByString:@"68a201e1a1"];
            
            // 身份验证确认信息
            NSString *str1 = arr[1];
            NSLog(@"str1:%@",str1);

            
            // 表的数据
            NSString *str2 = arr[2];
            NSLog(@"str2:%@",str2);
            self.cardNo = [str2 substringWithRange:NSMakeRange(0, 10)];

            
            // 数据域数据
            NSString *str3 = [str2 substringWithRange:NSMakeRange(14, str2.length-14-4)];
            NSLog(@"str3:%@",str3);
            
            NSMutableData *data1 = [self convertHexStrToData:str3];
            
            // 秘钥
            NSMutableData *keyData = [self convertHexStrToData:keyStr];
            
            // 解密
            NSMutableData *data2 = [self AES_NEW_AESDecrypt:data1 password:keyData];
            
            NSString *str4 = [self hexStringWithData:data2];
            NSLog(@"str4:%@",str4);
            
            NSUInteger length = 0;

            // 命令类型
            NSString *subStr1 = [str4 substringWithRange:NSMakeRange(0, 2*1)];
            NSLog(@"命令类型:%@",subStr1);
            length = length + subStr1.length;
            
            // 表类型
            NSString *subStr2 = [str4 substringWithRange:NSMakeRange(length, 2*1)];
            NSLog(@"表类型:%@",subStr2);
            [self.mStr appendFormat:@"表类型:%@\n",subStr2];
            length = length + subStr2.length;
            self.deviceType = subStr2;

            // 价格类型标志
            NSString *subStr3 = [str4 substringWithRange:NSMakeRange(length, 2*1)];
            NSLog(@"价格类型标志:%@",subStr3);
            [self.mStr appendFormat:@"价格类型标志:%@\n",subStr3];
            length = length + subStr3.length;
            self.fluidType = subStr3;

            
            // 卡区域号
            NSString *subStr4 = [str4 substringWithRange:NSMakeRange(length, 2*3)];
            NSLog(@"卡区域号:%@",subStr4);
            [self.mStr appendFormat:@"卡区域号:%@\n",subStr4];
            length = length + subStr4.length;
            self.cardRegionNo = subStr4;

            // 卡ID号
            NSString *subStr5 = [str4 substringWithRange:NSMakeRange(length, 2*5)];
            NSLog(@"卡ID号:%@",subStr5);
            [self.mStr appendFormat:@"卡ID号:%@\n",subStr5];
            length = length + subStr5.length;
            self.cardID = subStr5;

            
            // 周期开始时间
            NSString *subStr6 = [str4 substringWithRange:NSMakeRange(length, 2*5)];
            NSLog(@"周期开始时间:%@",subStr6);
            [self.mStr appendFormat:@"周期开始时间:%@\n",subStr6];
            length = length + subStr6.length;
            self.startTime = subStr6;


            // 周期间隔时间
            NSString *subStr7 = [str4 substringWithRange:NSMakeRange(length, 2*1)];
            NSLog(@"周期间隔时间:%@",subStr7);
            [self.mStr appendFormat:@"周期间隔时间:%@\n",subStr7];
            length = length + subStr7.length;
            self.intervalMonth = subStr7;

            
            // 价格版本号
            NSString *subStr8 = [str4 substringWithRange:NSMakeRange(length, 2*2)];
            NSLog(@"价格版本号:%@",subStr8);
            [self.mStr appendFormat:@"价格版本号:%@\n",subStr8];
            length = length + subStr8.length;
            self.VersionNumber = subStr8;

            
            // 阶梯量1
            NSString *subStr9 = [str4 substringWithRange:NSMakeRange(length, 2*6)];
            NSLog(@"阶梯量1:%@",subStr9);
            [self.mStr appendFormat:@"阶梯量1:%@\n",subStr9];
            length = length + subStr9.length;
            self.endAmount1 = subStr9;

            
            // 单价1
            NSString *subStr10 = [str4 substringWithRange:NSMakeRange(length, 2*4)];
            NSLog(@"单价1:%@",subStr10);
            [self.mStr appendFormat:@"单价1:%@\n",subStr10];
            length = length + subStr10.length;
            self.price1 = subStr10;

            
            // 阶梯量2
            NSString *subStr11 = [str4 substringWithRange:NSMakeRange(length, 2*6)];
            NSLog(@"阶梯量2:%@",subStr11);
            [self.mStr appendFormat:@"阶梯量2:%@\n",subStr11];
            length = length + subStr11.length;
            self.endAmount2 = subStr11;

            
            // 单价2
            NSString *subStr12 = [str4 substringWithRange:NSMakeRange(length, 2*4)];
            NSLog(@"单价2:%@",subStr12);
            [self.mStr appendFormat:@"单价2:%@\n",subStr12];
            length = length + subStr12.length;
            self.price2 = subStr12;

            
            // 阶梯量3
            NSString *subStr13 = [str4 substringWithRange:NSMakeRange(length, 2*6)];
            NSLog(@"阶梯量3:%@",subStr13);
            [self.mStr appendFormat:@"阶梯量3:%@\n",subStr13];
            length = length + subStr13.length;
            self.endAmount3 = subStr13;

            
            // 单价3
            NSString *subStr14 = [str4 substringWithRange:NSMakeRange(length, 2*4)];
            NSLog(@"单价3:%@",subStr14);
            [self.mStr appendFormat:@"单价3:%@\n",subStr14];
            length = length + subStr14.length;
            self.price3 = subStr14;

            
            // 分时时间1
            NSString *subStr15 = [str4 substringWithRange:NSMakeRange(length, 2*2)];
            NSLog(@"分时时间1:%@",subStr15);
            [self.mStr appendFormat:@"分时时间1:%@\n",subStr15];
            length = length + subStr15.length;
            self.timeArea1 = subStr15;

            
            // 分时价格1
            NSString *subStr16 = [str4 substringWithRange:NSMakeRange(length, 2*4)];
            NSLog(@"分时价格1:%@",subStr16);
            [self.mStr appendFormat:@"分时价格1:%@\n",subStr16];
            length = length + subStr16.length;
            self.timePrice1 = subStr16;

            
            // 分时时间2
            NSString *subStr17 = [str4 substringWithRange:NSMakeRange(length, 2*2)];
            NSLog(@"分时时间2:%@",subStr17);
            [self.mStr appendFormat:@"分时时间2:%@\n",subStr17];
            length = length + subStr17.length;
            self.timeArea2 = subStr17;

            
            // 分时价格2
            NSString *subStr18 = [str4 substringWithRange:NSMakeRange(length, 2*4)];
            NSLog(@"分时价格2:%@",subStr18);
            [self.mStr appendFormat:@"分时价格2:%@\n",subStr18];
            length = length + subStr18.length;
            self.timePrice2 = subStr18;

            
            // 分时时间3
            NSString *subStr19 = [str4 substringWithRange:NSMakeRange(length, 2*2)];
            NSLog(@"分时时间3:%@",subStr19);
            [self.mStr appendFormat:@"分时时间3:%@\n",subStr19];
            length = length + subStr19.length;
            self.timeArea3 = subStr19;

            
            // 分时价格3
            NSString *subStr20 = [str4 substringWithRange:NSMakeRange(length, 2*4)];
            NSLog(@"分时价格3:%@",subStr20);
            [self.mStr appendFormat:@"分时价格3:%@\n",subStr20];
            length = length + subStr20.length;
            self.timePrice3 = subStr20;

            
            // 定时价格
            NSString *subStr21 = [str4 substringWithRange:NSMakeRange(length, 2*4)];
            NSLog(@"定时价格:%@",subStr21);
            [self.mStr appendFormat:@"定时价格:%@\n",subStr21];
            length = length + subStr21.length;
            self.fixedPrice = subStr21;

            
            // 报警金额
            NSString *subStr22 = [str4 substringWithRange:NSMakeRange(length, 2*4)];
            NSLog(@"报警金额:%@",subStr22);
            [self.mStr appendFormat:@"报警金额:%@\n",subStr22];
            length = length + subStr22.length;
            self.alarmMoney = subStr22;

            
            // 可透支金额
            NSString *subStr23 = [str4 substringWithRange:NSMakeRange(length, 2*4)];
            NSLog(@"可透支金额:%@",subStr23);
            [self.mStr appendFormat:@"可透支金额:%@\n",subStr23];
            length = length + subStr23.length;
            self.maxOverMoney = subStr23;

            
            // 过流量
            NSString *subStr24 = [str4 substringWithRange:NSMakeRange(length, 2*1)];
            NSLog(@"过流量:%@",subStr24);
            [self.mStr appendFormat:@"过流量:%@\n",subStr24];
            length = length + subStr24.length;
            self.maxOverdraft = subStr24;

            
            // 累计量
            NSString *subStr25 = [str4 substringWithRange:NSMakeRange(length, 2*6)];
            NSLog(@"累计量:%@",subStr25);
            [self.mStr appendFormat:@"累计量:%@\n",subStr25];
            length = length + subStr25.length;
            self.Cumulant = subStr25;

            
            // 剩余金额
            NSString *subStr26 = [str4 substringWithRange:NSMakeRange(length, 2*6)];
            NSLog(@"剩余金额:%@",subStr26);
            [self.mStr appendFormat:@"剩余金额:%@\n",subStr26];
            length = length + subStr26.length;
            self.SurplusMoney = subStr26;

            
            // 过零金额
            NSString *subStr27 = [str4 substringWithRange:NSMakeRange(length, 2*6)];
            NSLog(@"过零金额:%@",subStr27);
            [self.mStr appendFormat:@"过零金额:%@\n",subStr27];
            length = length + subStr27.length;
            self.OverZeroMoney = subStr27;

            
            // 过流次数
            NSString *subStr28 = [str4 substringWithRange:NSMakeRange(length, 2*1)];
            NSLog(@"过流次数:%@",subStr28);
            [self.mStr appendFormat:@"过流次数:%@\n",subStr28];
            length = length + subStr28.length;
            self.OverFlowTimes = subStr28;

            
            // 磁攻击次数
            NSString *subStr29 = [str4 substringWithRange:NSMakeRange(length, 2*1)];
            NSLog(@"磁攻击次数:%@",subStr29);
            [self.mStr appendFormat:@"磁攻击次数:%@\n",subStr29];
            length = length + subStr29.length;
            self.MagAttTimes = subStr29;

            
            // 卡攻击次数
            NSString *subStr30 = [str4 substringWithRange:NSMakeRange(length, 2*1)];
            NSLog(@"卡攻击次数:%@",subStr30);
            [self.mStr appendFormat:@"卡攻击次数:%@\n",subStr30];
            length = length + subStr30.length;
            self.CardAttTimes = subStr30;

            
            // 表状态
            NSString *subStr31 = [str4 substringWithRange:NSMakeRange(length, 2*3)];
            NSLog(@"表状态:%@",subStr31);
            [self.mStr appendFormat:@"表状态:%@\n",subStr31];
            length = length + subStr31.length;
            self.MeterState = subStr31;

            
            // 当月累计量
            NSString *subStr32 = [str4 substringWithRange:NSMakeRange(length, 2*6)];
            NSLog(@"当月累计量:%@",subStr32);
            [self.mStr appendFormat:@"当月累计量:%@\n",subStr32];
            length = length + subStr32.length;
            self.CurrMonthTotal = subStr32;

            
            // 上月累计量
            NSString *subStr33 = [str4 substringWithRange:NSMakeRange(length, 2*6)];
            NSLog(@"上月累计量:%@",subStr33);
            [self.mStr appendFormat:@"上月累计量:%@\n",subStr33];
            length = length + subStr33.length;
            self.Last1MonthTotal = subStr33;

            
            // 当前单价
            NSString *subStr34 = [str4 substringWithRange:NSMakeRange(length, 2*4)];
            NSLog(@"当前单价:%@",subStr34);
            [self.mStr appendFormat:@"当前单价:%@\n",subStr34];
            length = length + subStr34.length;
            self.accPrice = subStr34;

            
            // 累计用气金额
            NSString *subStr35 = [str4 substringWithRange:NSMakeRange(length, 2*6)];
            NSLog(@"累计用气金额:%@",subStr35);
            [self.mStr appendFormat:@"累计用气金额:%@\n",subStr35];
            length = length + subStr35.length;
            self.sumUseMoney = subStr35;

            
            // 累计充值金额
            NSString *subStr36 = [str4 substringWithRange:NSMakeRange(length, 2*6)];
            NSLog(@"累计充值金额:%@",subStr36);
            [self.mStr appendFormat:@"累计充值金额:%@\n",subStr36];
            length = length + subStr36.length;
            self.sumRechargeMoney = subStr36;

            
            // 本周期使用量
            NSString *subStr37 = [str4 substringWithRange:NSMakeRange(length, 2*6)];
            NSLog(@"本周期使用量:%@",subStr37);
            [self.mStr appendFormat:@"本周期使用量:%@\n",subStr37];
//            length = length + subStr37.length;
            self.weekUseVolume = subStr37;

            
            if ([self.delegate respondsToSelector:@selector(bluetoothSendData)]) {
                [self.delegate bluetoothSendData];
            }
            
            self.dataMStr = nil;


        }
        
    }
    
//    self.rpmString = [self rpmStringWithHexString:hexString];

    
    
    // 测试

    //获取系统当前时间
    NSDate *currentDate = [NSDate date];
    //用于格式化NSDate对象
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    //设置格式：zzz表示时区
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    //NSDate转NSString
    NSString *currentDateString = [dateFormatter stringFromDate:currentDate];
//    [self.mStr appendFormat:@"%@:接收指令\n%@\n",currentDateString,data];
    
    
//    if ([self.delegate respondsToSelector:@selector(bluetoothUpdateriji:)]) {
//        [self.delegate bluetoothUpdateriji:self.mStr];
//    }
}


// 连接身份验证
- (void)verifyDevice {
    
    //  发送指令到设备
    
    // 固定指令
    NSMutableData *startData = [self convertHexStrToData:@"68A210A1E148850368"];
    
    // ------------数据域236B6E加密-------------------
    NSMutableData *plainData = [self convertHexStrToData:@"236B6E"];

    // 秘钥
    NSMutableData *keyData = [self convertHexStrToData:keyStr];
    
    NSMutableData *contentData = [self AES_NEW_AESEncrypt:plainData pass:keyData];
    
//    NSMutableData *contentData1 = [self AES_NEW_AESDecrypt:contentData password:keyData];

    
    // ----------------校验和----------------
    NSMutableData *data1 = [self convertHexStrToData:@"68A210A1E148850368236B6E"];
    
    Byte onTimeChargeOrder[1] = {0};
    onTimeChargeOrder[0] = [self calCheckSum2:data1];
    NSData *data2 = [NSData dataWithBytes:onTimeChargeOrder length:sizeof(onTimeChargeOrder)];
    NSLog(@"校验和:%@", data2);
    
    // ----------------帧结束符----------------
    NSMutableData *endData = [self convertHexStrToData:@"16"];

    NSMutableData *sendData = [NSMutableData data];
    [sendData appendData:startData];
    [sendData appendData:contentData];
    [sendData appendData:data2];
    [sendData appendData:endData];

    
    NSLog(@"发送连接身份验证指令:%@", sendData);
    
    NSLog(@"长度:%ld", [sendData length]);
    
    // 蓝牙发送最大字节20，所以分包发（一字节等于两字符）
    for (int i = 0; i < [sendData length]; i += 20) {
        // 预加 最大包长度，如果依然小于总数据长度，可以取最大包数据大小
        if ((i + 20) < [sendData length]) {
            NSString *rangeStr = [NSString stringWithFormat:@"%i,%i", i, 20];
            NSData *subData = [sendData subdataWithRange:NSRangeFromString(rangeStr)];
            
            NSLog(@"subData：%@",subData);
            
            if (self.characteristicWrite) {
                [self.fitNowPeripheral writeValue:subData forCharacteristic:self.characteristicWrite type:CBCharacteristicWriteWithoutResponse];

            }


//            //根据接收模块的处理能力做相应延时
//            usleep(20 * 1000);// 单位是微秒，所以这里是20毫秒，1000 微秒 = 1毫秒
        }
        else {
            NSString *rangeStr = [NSString stringWithFormat:@"%i,%i", i, (int)([sendData length] - i)];
            NSData *subData = [sendData subdataWithRange:NSRangeFromString(rangeStr)];

            if (self.characteristicWrite) {
                [self.fitNowPeripheral writeValue:subData forCharacteristic:self.characteristicWrite type:CBCharacteristicWriteWithoutResponse];
                
            }
            NSLog(@"subData1：%@",subData);
//            usleep(20 * 1000);
        }
    }

    
    // 测试
    //获取系统当前时间
    NSDate *currentDate = [NSDate date];
    //用于格式化NSDate对象
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    //设置格式：zzz表示时区
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    //NSDate转NSString
    NSString *currentDateString = [dateFormatter stringFromDate:currentDate];
    
//    [self.mStr appendFormat:@"%@:发送指令:\n%@\n",currentDateString,sendData];
}

// 充值写卡
- (void)writeCard:(NSString *)str
{
    //  发送指令到设备
    
    // 固定指令
    NSMutableData *startData = [self convertHexStrToData:@"68A210A1E100000000005968"];
    
    // ------------数据域236B6E加密-------------------
    NSMutableData *plainData = [self convertHexStrToData:str];
    
    // 秘钥
    NSMutableData *keyData = [self convertHexStrToData:keyStr];
    
    // 加密
    NSMutableData *contentData = [self AES_NEW_AESEncrypt:plainData pass:keyData];
    
    // 解密
    NSMutableData *contentData1 = [self AES_NEW_AESDecrypt:contentData password:keyData];
    NSLog(@"解密:%@",contentData1);
    
    // ----------------校验和----------------
    NSMutableData *data1 = [self convertHexStrToData:[NSString stringWithFormat:@"68A210A1E100000000005968%@",str]];
    
    Byte onTimeChargeOrder[1] = {0};
    onTimeChargeOrder[0] = [self calCheckSum2:data1];
    NSData *data2 = [NSData dataWithBytes:onTimeChargeOrder length:sizeof(onTimeChargeOrder)];
    NSLog(@"校验和:%@", data2);
    
    // ----------------帧结束符----------------
    NSMutableData *endData = [self convertHexStrToData:@"16"];
    
    NSMutableData *sendData = [NSMutableData data];
    [sendData appendData:startData];
    [sendData appendData:contentData];
    [sendData appendData:data2];
    [sendData appendData:endData];
    
    NSLog(@"发送充值写卡指令:%@", sendData);
    
    NSLog(@"长度:%ld", [sendData length]);
    
    // 蓝牙发送最大字节20，所以分包发（一字节等于两字符）
    for (int i = 0; i < [sendData length]; i += 20) {
        // 预加 最大包长度，如果依然小于总数据长度，可以取最大包数据大小
        if ((i + 20) < [sendData length]) {
            NSString *rangeStr = [NSString stringWithFormat:@"%i,%i", i, 20];
            NSData *subData = [sendData subdataWithRange:NSRangeFromString(rangeStr)];
            
            NSLog(@"subData：%@",subData);
            
            if (self.characteristicWrite) {
                [self.fitNowPeripheral writeValue:subData forCharacteristic:self.characteristicWrite type:CBCharacteristicWriteWithoutResponse];
                
            }
            
            
            //            //根据接收模块的处理能力做相应延时
            //            usleep(20 * 1000);// 单位是微秒，所以这里是20毫秒，1000 微秒 = 1毫秒
        }
        else {
            NSString *rangeStr = [NSString stringWithFormat:@"%i,%i", i, (int)([sendData length] - i)];
            NSData *subData = [sendData subdataWithRange:NSRangeFromString(rangeStr)];
            
            if (self.characteristicWrite) {
                [self.fitNowPeripheral writeValue:subData forCharacteristic:self.characteristicWrite type:CBCharacteristicWriteWithoutResponse];
                
            }
            NSLog(@"subData1：%@",subData);
            //            usleep(20 * 1000);
        }
    }
    
    
    // 测试
    //获取系统当前时间
    NSDate *currentDate = [NSDate date];
    //用于格式化NSDate对象
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    //设置格式：zzz表示时区
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    //NSDate转NSString
    NSString *currentDateString = [dateFormatter stringFromDate:currentDate];
    
    //    [self.mStr appendFormat:@"%@:发送指令:\n%@\n",currentDateString,sendData];

}

// 充值确认
- (void)rechargeConfirm {
    
    self.isRechargeConfirm = YES;
    
    //  发送指令到设备
    
    // 固定指令
    NSMutableData *startData = [self convertHexStrToData:@"68A210A1E100000000000268"];
    
    // ------------数据域236B6E加密-------------------
    NSMutableData *plainData = [self convertHexStrToData:@"2411"];
    
    // 秘钥
    NSMutableData *keyData = [self convertHexStrToData:keyStr];
    
    NSMutableData *contentData = [self AES_NEW_AESEncrypt:plainData pass:keyData];
    
    //    NSMutableData *contentData1 = [self AES_NEW_AESDecrypt:contentData password:keyData];
    
    
    // ----------------校验和----------------
    NSMutableData *data1 = [self convertHexStrToData:@"68A210A1E1000000000002682411"];
    
    Byte onTimeChargeOrder[1] = {0};
    onTimeChargeOrder[0] = [self calCheckSum2:data1];
    NSData *data2 = [NSData dataWithBytes:onTimeChargeOrder length:sizeof(onTimeChargeOrder)];
    NSLog(@"校验和:%@", data2);
    
    // ----------------帧结束符----------------
    NSMutableData *endData = [self convertHexStrToData:@"16"];
    
    NSMutableData *sendData = [NSMutableData data];
    [sendData appendData:startData];
    [sendData appendData:contentData];
    [sendData appendData:data2];
    [sendData appendData:endData];
    
    
    NSLog(@"发送充值确认指令:%@", sendData);
    
    NSLog(@"长度:%ld", [sendData length]);
    
    // 蓝牙发送最大字节20，所以分包发（一字节等于两字符）
    for (int i = 0; i < [sendData length]; i += 20) {
        // 预加 最大包长度，如果依然小于总数据长度，可以取最大包数据大小
        if ((i + 20) < [sendData length]) {
            NSString *rangeStr = [NSString stringWithFormat:@"%i,%i", i, 20];
            NSData *subData = [sendData subdataWithRange:NSRangeFromString(rangeStr)];
            
            NSLog(@"subData：%@",subData);
            
            if (self.characteristicWrite) {
                [self.fitNowPeripheral writeValue:subData forCharacteristic:self.characteristicWrite type:CBCharacteristicWriteWithoutResponse];
                
            }
            
            
            //            //根据接收模块的处理能力做相应延时
            //            usleep(20 * 1000);// 单位是微秒，所以这里是20毫秒，1000 微秒 = 1毫秒
        }
        else {
            NSString *rangeStr = [NSString stringWithFormat:@"%i,%i", i, (int)([sendData length] - i)];
            NSData *subData = [sendData subdataWithRange:NSRangeFromString(rangeStr)];
            
            if (self.characteristicWrite) {
                [self.fitNowPeripheral writeValue:subData forCharacteristic:self.characteristicWrite type:CBCharacteristicWriteWithoutResponse];
                
            }
            NSLog(@"subData1：%@",subData);
            //            usleep(20 * 1000);
        }
    }
    
    
    // 测试
    //获取系统当前时间
    NSDate *currentDate = [NSDate date];
    //用于格式化NSDate对象
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    //设置格式：zzz表示时区
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    //NSDate转NSString
    NSString *currentDateString = [dateFormatter stringFromDate:currentDate];
    
    //    [self.mStr appendFormat:@"%@:发送指令:\n%@\n",currentDateString,sendData];
    
    // 写卡结果(成功)
    [[NSNotificationCenter defaultCenter] postNotificationName:@"kWriteCardNotification" object:@"00"];

}


// 获取校验和
- (Byte)calCheckSum2:(NSData *)data{
    Byte chksum = 0;
    Byte *byte = (Byte *)[data bytes];
    for (NSUInteger i = 0; i < [data length]; i++){
        chksum += byte[i];
    }
    return chksum;
}

//将十六进制转化为十进制
- (NSString *)hexToDecimal:(NSString *)tmpStr
{
    NSString * temp10 = [NSString stringWithFormat:@"%lu",strtoul([tmpStr UTF8String],0,16)];

    return temp10;
}

//
//将十进制转化为十六进制
- (NSString *)decimalToHex:(uint16_t)tmpid
{
    NSString *nLetterValue;
    NSString *str =@"";
    uint16_t ttmpig;
    for (int i = 0; i<9; i++) {
        ttmpig=tmpid % 16;
        tmpid=tmpid / 16;
        switch (ttmpig)
        {
            case 10:
                nLetterValue =@"A";break;
            case 11:
                nLetterValue =@"B";break;
            case 12:
                nLetterValue =@"C";break;
            case 13:
                nLetterValue =@"D";break;
            case 14:
                nLetterValue =@"E";break;
            case 15:
                nLetterValue =@"F";break;
            default:
                nLetterValue = [NSString stringWithFormat:@"%u",ttmpig];
                
        }
        str = [nLetterValue stringByAppendingString:str];
        if (tmpid == 0) {
            break;
        }
        
    }
    return str;
}


//  NSData转换为16进制字符串
- (NSString *)hexStringWithData:(NSData *)data {
    Byte *bytes = (Byte *)[data bytes];
    NSString *hexStr = @"";
    for(int i = 0;i < [data length];i++)
    {
        NSString *newHexStr = [NSString stringWithFormat:@"%x",bytes[i] & 0xff];///16进制数
        if([newHexStr length]==1)
            hexStr = [NSString stringWithFormat:@"%@0%@",hexStr,newHexStr];
        else
            hexStr = [NSString stringWithFormat:@"%@%@",hexStr,newHexStr];
    }
    return hexStr;
}

// 16进制字符串转换成NSData
- (NSMutableData *)convertHexStrToData:(NSString *)str {
    if (!str || [str length] == 0) {
        return nil;
    }
    
    NSMutableData *hexData = [[NSMutableData alloc] initWithCapacity:8];
    NSRange range;
    if ([str length] % 2 == 0) {
        range = NSMakeRange(0, 2);
    } else {
        range = NSMakeRange(0, 1);
    }
    for (NSInteger i = range.location; i < [str length]; i += 2) {
        unsigned int anInt;
        NSString *hexCharStr = [str substringWithRange:range];
        NSScanner *scanner = [[NSScanner alloc] initWithString:hexCharStr];
        
        [scanner scanHexInt:&anInt];
        NSData *entity = [[NSData alloc] initWithBytes:&anInt length:1];
        [hexData appendData:entity];
        
        range.location += range.length;
        range.length = 2;
    }
    
    NSLog(@"hexdata: %@", hexData);
    return hexData;
}

// 加解密：采用AES128，模式AES-ECB,数据填充方式采用kCCOptionPKCS7Padding方式
// 加密方法
-(NSMutableData*)AES_NEW_AESEncrypt:(NSMutableData*)plain pass:(NSMutableData*)key

{
    
    // NSLog(@"key是%@",key);
    
    char keyPtr[kCCKeySizeAES128+1];
    
    memset(keyPtr,0,sizeof(keyPtr));
    
    [key getBytes:keyPtr length:sizeof(keyPtr)];
    
    //NSLog(@"加密的KEY是%s",keyPtr);
    
    NSData* data = [[NSData alloc]initWithData:plain];
    
    NSUInteger dataLength = [data length];
    
    size_t bufferSize = dataLength +kCCBlockSizeAES128;
    
    void *buffer = malloc(bufferSize);
    
    size_t numBytesEncrypted =0;
    
    CCCryptorStatus cryptStatus =CCCrypt(kCCEncrypt,
                                         
                                         kCCAlgorithmAES128,
                                         
                                         kCCOptionPKCS7Padding|kCCOptionECBMode,
                                         
                                         keyPtr,
                                         
                                         kCCBlockSizeAES128,
                                         
                                         NULL,
                                         
                                         [data bytes],
                                         
                                         dataLength,
                                         
                                         buffer,
                                         
                                         bufferSize,
                                         
                                         &numBytesEncrypted);
    
    if(cryptStatus ==kCCSuccess) {
        
        NSMutableData *resultData = [NSMutableData dataWithBytes:buffer length:numBytesEncrypted];
        NSLog(@"resultData:%@",resultData);
        return resultData;
        
    }
    
    free(buffer);
    
    return nil;
    
}

// 解密方法
-(NSMutableData*)AES_NEW_AESDecrypt:(NSMutableData*)encryptText password:(NSMutableData*)key

{
    
    char keyPtr[kCCKeySizeAES128+1];
    
    memset(keyPtr,0,sizeof(keyPtr));
    
    [key getBytes:keyPtr length:sizeof(keyPtr)];
    
    NSData*data=[[NSData alloc]initWithData:encryptText];
    
    NSUInteger dataLength = [data length];
    
    size_t bufferSize = dataLength +kCCBlockSizeAES128;
    
    void*buffer =malloc(bufferSize);
    
    size_t numBytesCrypted =0;
    
    CCCryptorStatus cryptStatus =CCCrypt(kCCDecrypt,
                                         
                                         kCCAlgorithmAES128,
                                         
                                         kCCOptionPKCS7Padding|kCCOptionECBMode,
                                         
                                         keyPtr,
                                         
                                         kCCBlockSizeAES128,
                                         
                                         NULL,
                                         
                                         [data bytes],
                                         
                                         dataLength,
                                         
                                         buffer,
                                         
                                         bufferSize,
                                         
                                         &numBytesCrypted);
    
    if(cryptStatus ==kCCSuccess) {
        
        NSMutableData *resultData = [NSMutableData dataWithBytesNoCopy:buffer length:numBytesCrypted];
        
        return resultData;
        
    }
    
    free(buffer);
    
    return nil;
    
}


@end
